<?php
header('Content-type: text/javascript; charset=utf-8');
?>
var tinyMCEImageList = new Array(
<?php

$output = array();
image_list();

for ($i=0;$i<sizeof($output);$i++) {
	echo $output[$i];	
	if ($i == sizeof($output) - 1) echo "\n";
	else echo ",\n";
}

function image_list($parent_id=null, $parent_folders='') {
	global $output, $db, $site, $env;
	
	if ($parent_id == null) {
		// get the top most folder
		$parent_id = $db->fetchOne("SELECT id FROM cms_images_folders WHERE site_id=? AND parent_id=0", $site['id']);
		if (!$parent_id) {
			exit;
		}
	}
	
	$images = $db->fetchAll("SELECT id, filename, caption FROM cms_images WHERE site_id=? AND folder_id=? ORDER BY caption, filename", array($site['id'], $parent_id));
	foreach($images as $image) {
		$image['id'] = str_pad($image['id'], 5, 0, STR_PAD_LEFT);
		//$image['parent_folders'] = $parent_folders ? "{$parent_folders} » {$subfolder['title']}" : $subfolder['title'];
		$image['label'] = $image['caption'] ? $image['caption'] : $image['filename'];
		$output[] = "['" . escape($parent_folders . $image['label'], 'javascript') . "', 'http://{$site['domain_name']}/images/{$image['id']}/" . escape($image['filename'], 'javascript') . "']";
		if (isset($env['image_profile'])) {
			foreach($env['image_profile'] as $name => $spec) {
				$output[] = "[' » " . escape($name, 'javascript') . "', 'http://{$site['domain_name']}/images/{$spec}/{$image['id']}/" . escape($image['filename'], 'javascript') . "']";
			}
			$output[] = "['', '']";
		}
	}
	
	$subfolders = $db->fetchAll("SELECT id, title FROM cms_images_folders WHERE site_id=? AND parent_id=?", array($site['id'], $parent_id));
	foreach($subfolders as $subfolder) {
		image_list($subfolder['id'], "{$parent_folders}{$subfolder['title']} » ");
	}

}


?>
);
